<?php
/**
* Controlller基类
*
* 本程序主要用来取得在Controller中使用的一些基本方法和基本变量
* 
* @category   Controller
* @package    Base
* @copyright  Copyright (c) ink工作室 (http://www.inkphp.com)
* @author     张旭刚
* @version    v1.0 beta
*/
class Controller{
    protected $tpl;
    public $app;
    public $m;
    public $a;
    public $g;
    public $p;
    public $r;
    private $db = false;
    public $dao = NULL;
    public function __construct($data) {
        $this->getTplObj();
        $this->g = $data['g'];
        $this->r = $data['r'];
        $this->p = $data['p'];
        $this->app = APP_NAME;
        $this->m = MODEL_NAME;
        $this->a = ACTION_NAME;
    }
    
    /**
     * @method 使用Session做登陆的检查。
     * @param string $name session名字
     * @param string $jumpUrl 检查不存在的话要跳转到得位置,一般是登陆页的地址
     * @return null;
     */
    protected function checkSessionLogin($name, $jumpUrl){
        if(empty($_SESSION[$name])){
            $this->jump($jumpUrl);
        }
    }
    
    protected function checkCookieLogin($name,$jumpUrl){
        $cookie = $this->X('Cookie', $name);
        $ck = $cookie->getCookie();
        if(empty($ck)){
            $this->jump($jumpUrl);
        }
    }


    /**
     * @method 魔术方法，当调用的Action不存在的话自动会进入这个方法
     * @param string $name Action的名字
     * @param string $params 此参数暂时无用处
     * @return html  
     */
    public function __call($name,$params = null){
        return $this->display($name);
    }

    public function json($encode = true){
        $this->tpl->json($encode);
    }
    
    final public function fetch($name = null){
        $path = $this->changeTpl($name);
        return $this->tpl->fetch($path);
    }
    
    /**
     * @method 此方法的主要功能是显示渲染页面。
     * @param string $name 模板名称，如果为空的话会自动变为Action的名字，无需扩展名
     * @param string $dest 要创建的静态文件的存放目录
     */
    final public function display($name = null){
        $path = $this->changeTpl($name);
        $this->tpl->display($path);
    }
    
    /**
     * @method 检查模板名字
     * @param sting $name 模板名称
     * @return string $path 模板路径
     */
    private function changeTpl($name){
        if(empty($name)){
            $name = $this->a;
        }
        $name = str_replace('.html','',$name);
        if($name == 'msg' || $name == 'upload'){
            $path = './core/Theme/Public/'.$name.'.html';
        }else{
            //$path = './Theme/'.__DEFAULT_THEME__.'/'.$this->app.'/'.$this->m.'/'.$name.'.html';
            $path = '../templates/'.$name.'.html';
        }
//        if(!file_exists($path)){
//            $this->error('template_is_not_exists:'.basename($path));
//        }
        return $path;
    }


    /**
     * @method 设置模板变量
     * @param string $name
     * @param anytype $data 
     */
    final public function assign($name, $data = null){
        if(!is_object($data)){
            $this->tpl->assign($name, $data);
        }
    }
    
    /**
     * @method 显示提示消息
     * @param string $msg 要显示的提示消息
     * @param type $status 提示类型：error，warring，success
     * @param string $jumpUrl 消息显示完成后要跳转的页面，默认为上一个页面
     */
    private function showMsg($msg, $status, $jumpUrl = null){
        $msgs = explode(':', $msg);
        if(count($msgs) == 2){
            $msg = L($msgs[0]).$msgs[1];
            $this->assign('msg', $msg);
        }else{
            $this->assign('msg', L($msg));
        }
        if($jumpUrl == '' || empty($jumpUrl)){
            $jumpUrl = 'return';
        }
        $this->assign('url', $jumpUrl);
        $this->assign('status', $status);
        $this->display('msg');
        exit;
    }
    
    /**
     * @method 成功提示消息
     * @param type $msg 消息文本
     * @param type $jumpUrl 跳转路径
     */
    public function success($msg, $jumpUrl = null){
        $this->showMsg($msg, 'success', $jumpUrl);
    }
    
    /**
     * @method 错误提示消息
     * @param type $msg 消息文本
     * @param type $jumpUrl 跳转路径
     */
    public function error($msg, $jumpUrl = null){
        $this->showMsg($msg, 'error', $jumpUrl);
    }
    /**
     * @method 警告消息
     * @param type $msg 消息文本
     * @param type $jumpUrl 跳转路径
     */
    public function warring($msg, $jumpUrl = null){
        $this->showMsg($msg, 'warring',$jumpUrl);
    }
    
//    public function __get($name){
//        if($name == 'db'){
//            return $this->getdb();
//        }
//    }
    /**
     * @method 连接数据库
     * @return object 返回数据库连接之后产生的实例
     */
//    private function getdb(){
//	$db = ADONewConnection(__DB_TYPE__);
//	$db->createdatabase = true;
//	if($pconnect){
//	   $db->PConnect(__DB_HOST__, __DB_USER__, __DB_PWD__, __DB_NAME__);
//	}else{
//	   $db->Connect(__DB_HOST__, __DB_USER__, __DB_PWD__, __DB_NAME__);
//	}
//	$db->Execute("set names utf8");
//	return $db;
//    }
    
    private function getdb(){
        $config['host'] = __DB_HOST__;
        $config['user'] = __DB_USER__;
        $config['pwd'] = __DB_PWD__;
        $config['dbName'] = __DB_NAME__;
        $db = new db($config);
        return $db;
    }
    
    
    /**
     * @method 取得Model实例的方法
     * @param string $name
     * @return object 返回Model的实例
     */
    protected function D($name = null){
        $model = $name.'Model';
        $public_path = __MODEL__.'/'.$model.'.class.php';
        if(file_exists($public_path)){
            include_once($public_path);
            if(class_exists($model)){
                if(!isset($this->$model)){
                    if($this->db == false){
                        $this->db = $this->getdb();
                    }
                    $this->$model = new $model($this->db,$name);
                    return $this->$model;
                }else{
                    return $this->$model;
                }
            }else{
                $public_path = __BASE__.'/Model.class.php';
                $model = 'Model';
                if(class_exists($model)){
                    if(!isset($this->$model)){
                        if($this->db == false){
                            $this->db = $this->getdb();
                        }
                        $this->$model = new $model($this->db,$name);
                        return $this->$model;
                    }else{
                        return $this->$model;
                    }
                }
            }
        }else{
            $public_path = __BASE__.'/Model.class.php';
            $model = 'Model';
            if(class_exists($model)){
                if(!isset($this->$model)){
                    if($this->db == false){
                        $this->db = $this->getdb();
                    }
                    $smodel = $name.$model;
                    $this->$smodel = new $model($this->db,$name);
                    return $this->$smodel;
                }else{
                    return $this->$smodel;
                }
            }
        }
    }

    /**
     * @method 取得第三方插件实例的方法
     * @param string $name 插件名称
     * @param string $params 插件实例化需要调用的参数
     * @return object 返回插件实例
     */
    protected function X($name = null,$params = null){
        $xpath = __LIB__.'/'.$name.'.class.php';
        if(!file_exists($xpath)){
            return 'lib_file_is_not_exist:'.$xpath;
        }else{
            include_once($xpath);
            if(!class_exists($name)){
                return 'lib_class_is_not_define:'.$name;
            }else{
                if(!empty($params)){
                    return new $name($params);
                }else{
                    return new $name();
                }
            }
        }
    }
    
    /**
     * @method 实例化模板类
     * @return string 返回模板实例
     */
    private function getTplObj(){
        $path = '../system/Smarty-2.6.26/libs/Smarty.class.php';
        include($path);
        $this->tpl = new Smarty();
        $this->tpl->template_dir = '../templates/';
        $this->tpl->compile_dir  = '../system/templates_c/';
        $this->tpl->config_dir   = '../system/configs/';
        $this->tpl->cache_dir    = '../system/cache/';

        $this->tpl->left_delimiter = '{{';
        $this->tpl->right_delimiter = '}}';
    }
//    private function getTplObj(){
//        $path = __BASE__.'/Template.class.php';
//        if(file_exists($path)){
//            include($path);
//            if(class_exists('Template')){
//                $this->tpl = new Template();
//            }else{
//                return 'template_class_bad';
//            }
//        }else{
//            return 'template_class_bad';
//        }
//    }
    
    /**
     * @method 公用上传页面 
     * 如需使用请重写该方法
     */
    public function upload(){
        $this->display();
    }
    
    /**
     * @method 公用上传方法如需使用请重写该方法
     */
    public function uploadFile(){
        $data = $_FILES['Filedata'];
        $file = $this->X('File');
        $limitType = array('jpg', 'jpeg', 'gif', 'png');
        $file->setLimitType($limitType);
        $file->setLimitSize(2048);
        $file->setIsRename(true);
        $file->setUploadPath('./Data/graphic/'.date('Y').'/'.date('m').'/'.date('d'));
        $d = $file->uploadFile($data);
        print_r($d);
    }
   
    /**
     * 使用网络文件，直接下载
     */
    public function downloadFile(){
        $url = $this->p['fileurl'];
        $file = $this->X('File');
        $limitType = array('jpg', 'jpeg', 'gif', 'png');
        $file->setLimitType($limitType);
        $file->setLimitSize(2048);
        $file->setIsRename(true);
        $file->setUploadPath('./Data/graphic/'.date('Y').'/'.date('m').'/'.date('d'));
        $data = $file->downloadFile($url);
        print_r($data);
    }
    
    public function getVerify(){
        $code = $this->X('Code');
        $code->showImage();
    }
    
    /**
     * @method 页面跳转
     * @param string $url 要跳转到得页面地址
     */
    protected function jump($url){
        header('location:'.$url);
    }
    
    /**
     * @method 获取一个不重复的随机字符串
     * @return string 
     */
    protected function getKey(){
        return uniqid().'_'.time();
    }
    


    public function __destruct(){
        unset($this->app);
        unset($this->a);
        unset($this->g);
        unset($this->m);
        unset($this->p);
        unset($this->r);
        unset($this->tpl);
    }
//----------------------------------------------------------------
	protected function _set_head_footer() {
		 $this->assign('zhead', $this->fetch('zhead.html'));
		 $this->assign('zmenu', $this->fetch('zmenu.html'));
		 $this->assign('zfooter', $this->fetch('zfooter.html'));
	}
	
	protected function _load_mdao_class($classname) {
		require_once( "../system/mdao/{$classname}.php" );
	}
	protected function _load_tdao_class($classname) {
		require_once( "../system/tdao/{$classname}.php" );
	}
	protected function _load_Class_DAO_OTHER() {
		require_once( "../system/Class_DAO_OTHER.php" );
	}
	protected function _load_php_file($filename, $path = null) {
		require_once( "../system/{$filename}" );
	}
    
}